import fg from "fast-glob";
import fs from "fs-extra";
import path from "path";
import { TaskResult } from "../../common/tasks/BastTask.js";
import { layatoolchain } from "../../layatoolchain.js";
import { toolchain } from '../../toolchain.js';
import { replaceInFileOrThrow } from "../../tools/vendor.js";
import { Nullable } from "../../typings.js";
import { LayaPostPublishBaseTask } from "./LayaPostPublishBaseTask.js";
import { LayaPreBuildTask } from "./LayaPreBuildTask.js";

export class LayaPostPublishWxgameTask extends LayaPostPublishBaseTask {
    async run(): Promise<TaskResult<void>> {
        // 写入verMD5到game.js
        const versionCode = await this.getVersionCode();
        const RootBaseJS = path.join(layatoolchain.vars.publishRoot, 'js/plat/root/RootBase.js');
        const RootBaseContent = await fs.readFile(RootBaseJS, 'utf-8');
        const newRootBaseContent = RootBaseContent.replace('$verMd5$', versionCode);
        await fs.writeFile(RootBaseJS, newRootBaseContent, 'utf-8');

        // 创建各个渠道的文件夹
        const pfs = this.cmdOption.gameIds.split(/,\s*/);
        for (const pf of pfs) {
            console.log('making project folder for:', pf);
            const wxFolder = path.join(layatoolchain.vars.publishRoot, `../wxproject_${pf}`);
            // 复制project目录
            await fs.copy(path.join(toolchain.params.workSpacePath, 'build/projectfiles', pf, 'common/project'), wxFolder);
            // 复制js目录
            await fs.copy(path.join(layatoolchain.vars.publishRoot, 'js'), path.join(wxFolder, 'js'));
            // 复制libs目录
            await fs.copy(path.join(layatoolchain.vars.publishRoot, 'libs'), path.join(wxFolder, 'libs'));
            // main.js插入渠道参数
            const mainJS = path.join(wxFolder, 'main.js');
            const buildConfig = layatoolchain.vars.buildConfigMap[pf];
            await replaceInFileOrThrow(mainJS, '// __builtInCfg__', 'window.__builtInCfg__ = ' + JSON.stringify(buildConfig, null, 2) + ';')
            // 增加分包game.js
            await fs.writeFile(path.join(wxFolder, 'js/subpackage/game.js'), 'console.log("subpackage running!");');
        }
        
        return { success: true, errorCode: 0, data: void 0 };
    }

    get dependencies(): Nullable<string[]> {
        return [LayaPreBuildTask.name];
    }
}
